/**
 * 商家相关接口
 * 包括新增商家、删除商家、商家列表（支持模糊）、修改商家
 */
// 引入express
const express = require("express")
// 引入数据库连接池
const pool = require("../../db/db")
// 引入封装后的响应结果
const Response = require("../../utils/ResponseData")
// 引入表单验证模块joi
const Joi = require("joi")

// 创建路由管理器
const router = express.Router()

/**
 * 商家查询接口（同时支持模糊查询+分页）
 * 请求url：http://localhost:3001/petBusiness/get?page=1&&pageSize=5&&keywords=
 * 请求方式：get
 */
router.get("/petBusiness/get", async (req, res) => {
    console.log("进入到了PetBusiness.js->/getBusiness请求：", req.query)
    // 表单校验
    // 配置校验规则
    let schema = Joi.object({
        keywords: Joi.string(),// 关键字，可以不传
        page: Joi.number().required(), // 当前页码，校验规则：必须是数值类型，非空
        pageSize: Joi.number().integer().max(10).required(),// 每页显示条数，校验规则：整数，10条以内，非空
    })
    // 校验
    let { error, value } = schema.validate(req.query)
    if (error) {
        // 校验不通过
        res.send(Response.error(error))
        return
    }

    // 校验通过
    try {
        let { page, pageSize, keywords } = req.query
        // 计算每页开始位置：每页开始位置 = (当前页码 - 1) * 每页显示条数
        let startIndex = (page - 1) * pageSize
        // 将pageSize转换为整数
        pageSize = pageSize ? parseInt(pageSize) : 5
        // 处理keywords
        if (!keywords) {
            keywords = ''
        }
        // 编写sql：查询每页显示的数据 '%ss%'
        const sql = "select * from (select * from business where b_name like ?)b1 limit ?,?"
        // 执行sql
        const result = await pool.querySync(sql, [`%${keywords}%`, startIndex, pageSize])

        // 编写sql：查询总条数
        const sql2 = "select count(b_id) as count from (select * from business where b_name like ?)b1"
        // 执行sql
        const result2 = await pool.querySync(sql2, [`%${keywords}%`])
        // 获取查询到的总条数
        const total = result2[0].count

        // 将数据响应到前端
        res.send(Response.success({ page: parseInt(page), pageSize: pageSize, total, result }))

    } catch (e) {
        res.send(Response.error(e))
    }

})


/**
 * 添加商家接口 
 * 请求url：http://localhost:3001/petBusiness/add
 * 请求method:post
 * 请求参数：表单
 */
router.post("/petBusiness/add", (req, res) => {
    console.log("进入到了PetBusiness.js->/petBusiness/add：", req.body)
    // 从表单中解构表单数据
    let { b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer } = req.body // req.body 获取表单数据，req.query获取地址栏中的?key=value&&key=value
    // 封装校验规则
    let schema = Joi.object({
        b_img: Joi.string().required(),// 字符串，非空
        b_name: Joi.string().required(),// 字符串，非空
        b_price: Joi.number().required(),// 数值，非空
        b_JS: Joi.string().required(),// 字符串，非空
        b_score: Joi.number().required(),
        b_feature: Joi.string().required(),
        b_city: Joi.string().required(),
        b_city_detail: Joi.string().required(),
        b_offer: Joi.string().required()
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 校验成功
    // 编写sql
    const sql = `insert into business(b_img,b_name,b_price,b_JS,b_score,b_feature,b_city,b_city_detail,b_offer) values(?,?,?,?,?,?,?,?,?)`
    // 执行sql
    pool.query(sql, [b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer], (err, result) => {
        if (err) {
            res.send(Response.error("商家添加失败！"))
            return
        }
        res.send(Response.success(null, "商家添加成功！"))
    })

})

/**
 * 通过id查询商家接口
 * 请求url：http://localhost:3001/petBusiness/getById?b_id=1
 * 请求method：get
 * 请求参数：req.query 
 */
router.get("/petBusiness/getById", (req, res) => {
    // 获取前端传递的参数
    let { b_id } = req.query
    // 校验规则
    let schema = Joi.object({
        b_id: Joi.number().required()
    })
    // 校验
    let { error, value } = schema.validate(req.query)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 编写sql
    const sql = "select * from business where b_id=?"
    // 执行sql
    pool.query(sql, [b_id], (error, result) => {
        if (error) {
            res.send(Response.error("商家信息查询失败！"))
            return
        }
        if (result && result.length != 0) {
            res.send(Response.success(result[0]))
        } else {
            res.send(Response.error("未查询到相关商家！"))
        }
    })

})


/**
 * 根据id修改商家信息
 * 请求url:http://localhost:3001/petBusiness/update
 * 请求method:post
 * 请求params:表单->req.body
 */
router.post("/petBusiness/update", (req, res) => {
    console.log("进入到了PetBusiness.js->/petBusiness/update：", req.body)
    // 从表单中解构表单数据
    let { b_id, b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer } = req.body // req.body 获取表单数据，req.query获取地址栏中的?key=value&&key=value
    // 封装校验规则
    let schema = Joi.object({
        b_id: Joi.number().required(),
        b_img: Joi.string().required(),// 字符串，非空
        b_name: Joi.string().required(),// 字符串，非空
        b_price: Joi.number().required(),// 数值，非空
        b_JS: Joi.string().required(),// 字符串，非空
        b_score: Joi.number().required(),
        b_feature: Joi.string().required(),
        b_city: Joi.string().required(),
        b_city_detail: Joi.string().required(),
        b_offer: Joi.string().required()
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 编写sql
    const sql = "update business set b_img=?,b_name=?,b_price=?,b_JS=?,b_score=?,b_feature=?,b_city=?,b_city_detail=?,b_offer=? where b_id=?"
    // 执行sql
    pool.query(sql, [b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer, b_id], (err, result) => {
        if (err) {
            res.send(Response.error("商家信息修改失败！"))
            return
        }
        res.send(Response.success(null, "商家信息修改成功！"))
    })
})
/**
 * 根据id删除商家信息
 * 请求url：http://localhost:3001/petBusiness/delete?b_id=1
 * 请求method：get
 */
router.get("/petBusiness/delete", (req, res) => {
    let { b_id } = req.query;
    // 校验规则
    const schema = Joi.object({
        b_id: Joi.number().required()
    })
    // 校验
    const { error, value } = schema.validate(req.query)
    if (error) {
        res.send(Response.error("商家编号不能为空！"))
        return
    }
    // 编写sql
    const sql = "delete from business where b_id=?"
    // 执行sql
    pool.query(sql, [b_id], (error, result) => {
        if (error) {
            res.send(Response.error("商家信息删除失败！"))
            return
        }
        res.send(Response.success(null, "商家信息删除成功！"))
    })
})
module.exports = router